<template>
	<image class="imgs-top imgs" style="width: 750rpx;" src="/static/login/login-top2.png" mode="widthFix"></image>
	<view class="login-page">
		<!-- 头部 -->
		<view class="login-page-header">
			<view class="image-content">
				<image style="width: 150rpx; " src="/static/login/MF logo-1.png" mode="widthFix"></image>
			</view>
			<view class="login-langType" style="width:240rpx;">
				<gui-segmented-control :items="cates" :current="langIndex" borderRadius="40rpx"
					customStyle="border-radius:40rpx;height:40rpx;" @change="switchLanguage">
				</gui-segmented-control>
			</view>
			<view class="title">
				<text class="title-tip font">MFL-Smart {{ $t('mexico.login') }}</text>
				<text class="title-desc ">👏{{ $t('mexico.welcomeEletile') }} <text
						style="font-style: italic;">PAD</text>
					{{ $t('mexico.platform') }}</text>
			</view>
		</view>
		<!-- 中间表单 -->
		<view class="login" style="padding:10rpx;">
			<view style="margin-top:20rpx;">
				<form @submit="submit">
					<input type="text" class="login-input" name="username" :value="data.username"
						:placeholder="$t('mexico.pleaseUser')" />
					<input type="password" class="login-input" name="password"
						:placeholder="$t('mexico.pleasePassword')" v-model="data.password" />
					<!-- <input class="login-input" name="username" :value="data.username"  type="text" :placeholder="$t('mexico.pleaseUser')" clearable /> -->
					<!-- <input class="login-input" password v-model="data.password" type="text" :placeholder="$t('mexico.pleasePassword')" clearable /> -->
					<view class="gui-margin-top checkbox">
						<checkbox-group @change="checkboxChange()">
							<checkbox class="checkbox-check" :checked="data.checked === true"
								placeholder-style="color:#fff" />
						</checkbox-group>

						<text class="gui-text-small checkbox-spec">{{ $t('login.rememb')
							}}</text>
					</view>
					<view style="margin-top:38rpx;">
						<button type="default" class="gui-button gui-bg-primary gui-noborder" formType="submit"
							style="border-radius:50rpx;">
							<text class="gui-color-white gui-button-text">{{ $t('login.login') }}</text>
						</button>
					</view>
					<view style="margin-top:38rpx;">
						<button type="primary" plain="true" class="gui-button borderbut" style="border-radius:50rpx;"
							@click="handelServeSeting">
							<text class="gui-color-white gui-button-text color">{{
					$t("navigationBar.configurationServices") }}</text>
						</button>
					</view>
				</form>
			</view>
		</view>
		<!-- 服务配置弹框 -->
		<uni-popup ref="inputDialog" type="dialog">
			<view class="input-dialog-box">
				<view class="inputDialog-title">
					<view class="line"></view>
					<view class="title">{{ $t("navigationBar.serviceSetting") }}</view>
					<view class="line"></view>
				</view>
				<form class="form" @submit="formSubmit">
					<view class="uni-form-item">
						<view class="title">{{ $t("navigationBar.address") }}：</view>
						<uni-easyinput class="uni-mt-5" suffixIcon="list" v-model="data.adress"
							placeholder="示例http://172.16.100.133" @iconClick="iconClick"></uni-easyinput>
					</view>
					<view class="inputDialog-bottom">
						<button class="button" type="default" @click="handelCloseServeSeting">{{ $t("popup.cancel")
							}}</button>
						<button class="button sure" type="primary" form-type="submit">{{ $t("popup.confirm")
							}}</button>
					</view>
				</form>
			</view>
		</uni-popup>
		<!--最底部弹出的选择服务的列表-->
		<uni-popup ref="baseServiceListDialog" type="bottom">
			<view class="ServiceContainer">
				<view class="ServiceItem" v-for="(item, index) in servcieitemList.itemList" :key="index"
					@click="setBaseServcie(index)">
					<text>{{ item }}</text>
					<view @click.stop="removeBaseServieItem(item)">
						<uni-icons type="closeempty" size="26"></uni-icons>
					</view>

				</view>
				<view class="baseServiceListDialogCancel" @click="cancelServiceDialog()">{{ $t("popup.cancel") }}
				</view>
			</view>
		</uni-popup>
	</view>
	<image class="imgs-bottom imgs" style="width: 750rpx;" src="/static/login/login_bottom_bg.jpg" mode="widthFix">
	</image>
</template>


<script setup>
import { getLang } from '@/locale/index';
import { reLaunch } from '@/utils/routerSkip.js'
import graceChecker from "@/Grace6/js/checker.js";
import { regExpDomainName } from '@/utils/index.js'
import { logIn, getUserPermission, getCurrentUser, getDetailByCodeId } from '@/api/api.js';
import { TOKEN, FINE_GRIT, PREMISSIONS_PAGE, HISTORY_SET_BASEURL, SET_BASEURL, USERINFO, USERNAME, PASSWORD, PRINT_BASE } from '@/constant/index.js'
import { TEST_URL, PROD_URL, PRINT_BASE_URL } from '@/constant/config.js'
import { reactive, ref, onMounted, computed, watch } from "vue";
import { useI18n } from 'vue-i18n';
import { useStore } from "vuex";

let store = useStore();
const { t } = useI18n();
let isAndroid = ref(false);
let langIndex = ref();
let inputDialog = ref(null)
let baseServiceListDialog = ref(null)

let data = reactive({
	username: uni.getStorageSync(USERNAME) || '',
	password: uni.getStorageSync(PASSWORD) || '',
	serveSetingBool: false,
	adress: uni.getStorageSync(SET_BASEURL) || "http://172.16.100.133",
	checked: uni.getStorageSync(PASSWORD) != '' || false
})
let langTypes = ["zh-Hans", "en","es"]

let cates = computed(() => {
	return [t('login.simplified'), t('login.english'),t('login.spain')]
})
let servcieitemList = reactive({ itemList: [] });

data.serveSetingBool = computed(() => {
	return store.state.serveSetingBool
})

//把扫描条码变为物料集合的二维数组
watch(() => data.serveSetingBool, (newVal) => {
	if (newVal) {
		setTimeout(() => {
			inputDialog.value.open();
		}, 1000)
	}
}, {
	immediate: true,
	deep: true
});
onMounted(() => {
	let systemInfo = uni.getSystemInfoSync();
	//判断当前用户机型是否为安卓坏境
	isAndroid.value = systemInfo.platform.toLowerCase() === 'android';
	let langType = uni.getLocale()
	langIndex.value = langTypes.findIndex(x => x == langType)
})
const formSubmit = (e) => {
	if (!regExpDomainName(data.adress)) {
		uni.showToast({
			title: t('pageTranslation.addressCantMeet'),
			icon: "none"
		});
		return
	}
	uni.setStorageSync(SET_BASEURL, data.adress)
	let historySetBaseList = uni.getStorageSync(HISTORY_SET_BASEURL) || []
	// 判断与历史数据是否重复
	let isRepetition = historySetBaseList.some((item) => {
		return item == data.adress
	})
	if (!isRepetition) {
		historySetBaseList.unshift(data.adress);
		historySetBaseList = historySetBaseList.length >= 3 ? historySetBaseList.slice(0, 3) : historySetBaseList
		uni.setStorageSync(HISTORY_SET_BASEURL, historySetBaseList)
	}
	inputDialog.value.close();
	try {
		plus.runtime.restart()
	} catch (error) {

	}
}
const handelCloseServeSeting = () => {
	store.commit('updateServeSetingBool', 0)
	inputDialog.value.close();
}
const handelServeSeting = () => {
	inputDialog.value.open();
}
const iconClick = () => {
	servcieitemList.itemList = uni.getStorageSync(HISTORY_SET_BASEURL) || []
	if (!servcieitemList.itemList.length) {
		uni.showToast({
			title: t('JsInternational.noRelatedRecord'),
			icon: "none"
		});
		return
	}
	//弹出选择服务的窗口
	baseServiceListDialog.value.open();
}

//选择某个服务
function setBaseServcie(index) {
	data.adress = servcieitemList.itemList[index]
	baseServiceListDialog.value.close()
}
//移除某个服务
function removeBaseServieItem(item) {
	servcieitemList.itemList = servcieitemList.itemList.filter(e => e != item)
	uni.setStorageSync(HISTORY_SET_BASEURL, servcieitemList.itemList)
	baseServiceListDialog.value.close()
}

//取消
function cancelServiceDialog() {
	baseServiceListDialog.value.close()
}

// 登录操作
function submit(e) {
	if (data.checked) {
		uni.setStorageSync(PASSWORD, data.password)
	} else {
		uni.removeStorage({ //选中之后取消删除存储的密码
			key: PASSWORD,
			success() {
				console.log('删除成功')
			}
		})
	}
	// 表单数据
	var formData = e.detail.value;
	// 利用 graceUI 的表单验证工具进行验证
	//定义表单规则
	var rule = [
		// {
		// 	name: "username",
		// 	checkType: "string",
		// 	checkRule: "5,50",
		// 	errorMsg: t('login.account-remind')
		// },
		// {
		// 	name: "password",
		// 	checkType: "string",
		// 	checkRule: "6,100",
		// 	errorMsg: t('login.password-remind')
		// },
	];
	var checkRes = graceChecker.check(formData, rule);
	uni.setStorageSync(TOKEN, null);
	// 登录
	if (checkRes) {
		logIn({
			username: formData.username,
			password: formData.password,
			scope: 'server',
			grant_type: 'password'
		}).then(res => {
			let data = res
			if (data.access_token?.length > 0) {
				uni.setStorageSync(USERNAME, formData.username)
				let token = data.access_token;
				uni.setStorageSync(TOKEN, token);
				// 获取用户信息
				getUserInfo(token)
				// 获取用户权限信息
				// getUserPermissionFn()
			} else {
				uni.showToast({
					title: data.msg,
					icon: "none"
				});
			}
		}).catch((err) => {
			uni.showToast({
				title: t('JsInternational.requestFailed'),
				icon: "none"
			});
		})
	} else {
		uni.showToast({
			title: graceChecker.error,
			icon: "none"
		});
	}
	let serverIp
	// 获取打印机的服务器地址
	// getDetailByCodeId().then(res => {
	// 	console.log('服务器ip地址' + res.value)
	// 	serverIp = res.value
	// 	uni.setStorageSync(PRINT_BASE, serverIp)
	// 	let printId = uni.getStorageSync(PRINT_BASE)
	// 	let printUrl = printId.length > 0 ? printId : PRINT_BASE_URL

	// })
}
// 获取用户信息
async function getUserInfo(token) {
	let res = await getCurrentUser(token)
	if (res) {
		uni.setStorageSync(USERINFO, res.data.sysUser);
		// uni.showToast({
		// 	title: t('login.login-success'),
		// 	icon: "none"
		// });
		uni.setStorageSync(FINE_GRIT, res.data.permissions);
		uni.setStorageSync(PREMISSIONS_PAGE, res.data.permissions);
		// 获取权限
		getUserPermissionFn()
		// setTimeout(() => {
		// 	reLaunch({
		// 		url: '/pages/index/index'
		// 	});
		// }, 1000)
	} else {
		uni.showToast({
			title: t('JsInternational.userInformationFailed'),
			icon: "none"
		});
	}
}
// 获取用户权限
function getUserPermissionFn() {
	getUserPermission().then(res => {
		if (res.data.menu?.length) {
			uni.showToast({
				title: t('login.login-success'),
				icon: "none"
			});
			uni.setStorageSync(FINE_GRIT, res.data.button);
			uni.setStorageSync(PREMISSIONS_PAGE, res.data.menu);
			setTimeout(() => {
				reLaunch({
					url: '/pages/index/index'
				});
			}, 1000)
		}
	})
}

// 语言切换
function switchLanguage(index) {
	console.log(index)
	let type = langTypes[index];
	// #ifdef APP-PLUS
	if (isAndroid) {
		uni.showModal({
			content: t('login.language-change-confirm'),
			success: (res) => {
				if (res.confirm) {
					langIndex.value = index
					getLang(type)
				}
			}
		})
	} else {
		langIndex.value = index
		getLang(type)
	}
	// #endif
	// #ifndef APP-PLUS
	getLang(type)
	langIndex.value = index
	// #endif
}
// 点击记住密码存储到本地
const checkboxChange = () => {
	data.checked = !data.checked
	// console.log(data.checked)
}
</script>

<style lang="scss" scoped>
page {
	background-color: white !important;
}

.imgs {
	user-select: none;
	display: block;
	position: absolute;
	left: 0;
	width: 100%;
	height: 100%;
}

.imgs-top {
	top: 0;
}

.imgs-bottom {
	bottom: 0;
}

.login-page {
	padding: 250rpx 32rpx;
	overflow: hidden;

	&-header {
		display: flex;
		flex-direction: row;
		position: relative;
		border-width: 4px;
		border-color: rgb(99 102 241);

		.title {
			display: flex;
			flex-direction: column;
			justify-content: space-around;
		}

		.title-tip {
			font-family: ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
			--tw-text-opacity: 1;
			display: block;
			color: rgba(0, 0, 0, 0.9);
			font-size: 1.5rem;
			font-weight: 600;
		}

		.title-desc {
			color: rgb(203 213 225);
			font-weight: 500;
			font-size: 30rpx;
		}
	}

	.login-langType {
		position: absolute;
		top: -240rpx;
		left: -20rpx;
		.gui-bg-white{
			display: flex;
			justify-content: center;
			align-items: center;
		}
	}

}

.login-input {
	font-size: 32rpx;
	padding: 25.6rpx 48rpx;
	background-color: #F7F8F9;
	border-radius: 13rpx;
	margin: 32rpx 0;
	width: calc(100% - 96rpx);
}

.login-logo {
	width: 180rpx;
	height: 180rpx;
	font-size: 80rpx;
	text-align: center;
	line-height: 120rpx;
	padding: 30rpx;
	border-radius: 18rpx;
}

.other-login-icons {
	width: 88rpx;
	height: 88rpx;
	text-align: center;
	font-size: 70rpx;
	margin: 20rpx;
}

.login {
	position: relative;
	padding-bottom: 40rpx;
	// height: calc(100vh - 100rpx);

	::v-deep .gui-segmented-control-item {
		height: 40rpx;
		line-height: 40rpx;
	}


}

.inputDialog-title {
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 30rpx;
	height: 100rpx;
	color: #333;

	.title {
		margin: 0rpx 24rpx;
	}

	.line {
		width: 25%;
		background: #333;
		height: 1rpx;
	}
}

.form {
	background: #fff;

	.uni-form-item {
		display: flex;
		align-items: center;
		box-sizing: border-box;
		padding: 24rpx;
		background: #fff;
		overflow: hidden;
		font-size: 30rpx;

		.title {
			color: #333;
			width: 120rpx;
		}

		.inputBox {
			flex: 1;
			border: 1rpx solid #A5A5A5;
			border-radius: 10rpx;
			height: 70rpx;
			padding: 0rpx 10rpx;
			box-sizing: border-box;
		}

		.uni-input {
			width: 100%;
			color: #333;
			height: 100%;
			font-size: 30rpx;
		}
	}

	// .checkbox {
	// 	margin-top: 30rpx;
	// 	display: flex;
	// 	color: #fff;
	// 	align-items: center;
	// 	justify-content: flex-end;
	// }
}

.borderbut {
	background: #fff !important;
	// border: 2rpx solid #008AFF !important;
}

.color {
	color: #008AFF !important;
}

.inputDialog-bottom {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 24rpx;
	box-sizing: border-box;

	.button {
		margin: 0rpx !important;
		color: #666;
		width: 48%;
	}

	.sure {
		background-color: #008AFF !important;
		color: #fff;
	}

}

.checkbox {
	display: flex;
	flex-direction: row;
	line-height: 100%;

	&-check {
		width: 10%;
		text-align: right;
		box-sizing: border-box;
		// margin-left: 10rpx;
	}

	&-spec {
		flex: 1;
		font-size: 28rpx;
		padding-left: 10rpx;
		line-height: 160%;
	}
}

.ServiceContainer {
	padding: 15rpx;
	display: flex;
	flex-direction: column;
	align-items: flex-start;
	justify-content: center;
}

.ServiceItem {
	background-color: #fff;
	height: 80rpx;
	line-height: 80rpx;
	display: inline-flex;
	flex-direction: row;
	justify-content: space-between;
	align-items: center;
	width: 99%;
	padding-left: 10rpx;
	border-bottom: 2rpx solid #ededed;
}

.baseServiceListDialogCancel {
	text-align: center;
	background-color: #fff;
	height: 80rpx;
	line-height: 80rpx;
	width: 100%;
	border-radius: 10rpx;
	margin-top: 20rpx;
}
</style>
